package com.it.schoolbookshop_back.controller;

import com.it.schoolbookshop_back.entities.dto.RatingRequestDTO;
import com.it.schoolbookshop_back.entities.po.Rating;
import com.it.schoolbookshop_back.entities.po.Result;
import com.it.schoolbookshop_back.service.RatingService;
import com.it.schoolbookshop_back.utils.UserContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 评分相关控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/ratings")
public class RatingController {
    
    @Autowired
    private RatingService ratingService;
    
    /**
     * 提交评分
     * 
     * @param ratingRequest 评分请求数据
     * @return 评分结果
     */
    @PostMapping
    public Result<Object> submitRating(@RequestBody RatingRequestDTO ratingRequest) {
        // 从Token中获取当前用户ID
        Integer raterId = UserContext.getUserId();
        if (raterId == null) {
            return Result.unauthorized();
        }
        
        try {
            // 创建评分实体
            Rating rating = new Rating();
            rating.setTransactionId(ratingRequest.getTransaction_id());
            rating.setRaterId(raterId);
            rating.setScore(ratingRequest.getScore());
            rating.setComment(ratingRequest.getComment());
            
            // 保存评分记录
            boolean success = ratingService.createRating(rating);
            if (success) {
                log.info("用户{}提交评分成功，交易：{}", 
                    raterId, ratingRequest.getTransaction_id());
                return Result.success("评价成功", new HashMap<>());
            } else {
                log.error("用户{}提交评分失败", raterId);
                return Result.failed("评价失败，请确认您是交易的买方且交易已完成");
            }
        } catch (Exception e) {
            log.error("提交评分失败", e);
            return Result.failed("评价失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取当前用户的评分记录（包括作为评分人和被评分人）
     * 
     * @return 评分记录列表
     */
    @GetMapping
    public Result<Map<String, Object>> getMyRatings() {
        // 从Token中获取当前用户ID
        Integer userId = UserContext.getUserId();
        if (userId == null) {
            return Result.unauthorized();
        }
        
        try {
            // 获取用户相关的所有评分记录
            List<Rating> ratings = ratingService.getRatingsByUserId(userId);
            
            Map<String, Object> resultMap = new HashMap<>();
            resultMap.put("ratings", ratings);
            
            return Result.success("获取评价成功", resultMap);
        } catch (Exception e) {
            log.error("获取用户评分记录失败", e);
            return Result.failed("获取评分记录失败：" + e.getMessage());
        }
    }

    /**
     * 根据交易ID和评分人ID查询评分记录
     */
    @GetMapping("/transaction/{transactionId}")
    public Result<Rating> getRatingByTransaction(
            @PathVariable Integer transactionId) {
        Integer currentUserId = UserContext.getUserId();
        if (currentUserId == null) {
            return Result.unauthorized();
        }
        
        try {
            Rating rating = ratingService.getRatingByTransactionAndRater(transactionId, currentUserId);
            if (rating != null) {
                return Result.success("获取评价成功", rating);
            }
            return Result.failed("未找到相关评价");
        } catch (Exception e) {
            log.error("获取交易评价失败", e);
            return Result.failed("获取评价失败：" + e.getMessage());
        }
    }
} 